<template>
  <el-dialog title="任务详情" :close-on-click-modal="false" append-to-body :visible.sync="visible" lock-scroll
    width="1000px">
    <div class="topSty">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="选择系统" prop="systemId">
          <el-select v-model="queryParams.systemId" placeholder="请选择客户" style="width: 240px" @change="changeSystem">
            <el-option v-for="i in systemOptions" :key="i.id" :label="i.name" :value="i.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择设备" prop="deviceId">
          <el-select v-model="queryParams.deviceId" placeholder="请先选择系统" style="width: 240px">
            <el-option v-for="i in facOptions" :key="i.id" :label="i.name" :value="i.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-form>
        <el-form-item>
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-row :gutter="24">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane :label="item.name" :name="item.id + ''" v-for="item in tabList" :key="item.id"></el-tab-pane>
        </el-tabs>
        <el-table :data="tableList" id="chartTableExpand" style="width: 100%" ref="chartTable"
          @expand-change="handleRowClick" row-key="floorId">
          <el-table-column type="expand" class="childrenTableSty">
            <template slot-scope="scope">
              <el-table :ref="'expandTable' + scope.row.id" :data="scope.row.children" style="width: 90%"
                v-loading="expandLoading" border>
                <el-table-column type="index" width="50" label="序号" align="center"></el-table-column>
                <el-table-column label="设备名称" prop="deviceName" align="center"></el-table-column>
                <el-table-column label="已完成" prop="complete" align="center"></el-table-column>
                <el-table-column label="未完成" prop="total" align="center">
                  <template slot-scope="scope">
                    {{ scope.row.total - scope.row.complete }}
                  </template>
                </el-table-column>
                <el-table-column label="是否合格" prop="passStatus" align="center">
                  <template slot-scope="scope">
                    {{ scope.row.passStatus == 2 ? '不合格' : '合格' }}
                  </template>
                </el-table-column>
                <el-table-column label="一级消防注册工程师" prop="engineerName" align="center"></el-table-column>
                <el-table-column label="中级消防设施操作员" prop="operatorName" align="center"></el-table-column>
              </el-table>
              <pagination :total="getTotal(scope.row)" :page.sync="queryAll[scope.row.floorId].pageNum"
                :limit.sync="queryAll[scope.row.floorId].pageSize" @pagination="handlePagination(scope.row, $event)" />
            </template>
          </el-table-column>
          <el-table-column label="楼层" prop="floor"></el-table-column>
          <el-table-column label="系统" prop="systemName" align="center"></el-table-column>
          <el-table-column label="数量" prop="total"></el-table-column>
          <el-table-column label="已完成" prop="complete"></el-table-column>
          <el-table-column label="是否合格" prop="passStatus">
            <template slot-scope="scope">
              {{ scope.row.passStatus == 1 ? "合格" : "不合格" }}
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getList" />
      </el-row>
    </div>
    <facDetail v-if="facDetailVisible" ref="facDetail"></facDetail>
  </el-dialog>
</template>
<script>
import {
  getBuildingFloorList,
  getDeviceTree,
  updateBuildFloor,

} from "@/api/system/building";
import {
  getPlanTaskListQuery,
  getProjectPlanBuildingList,
  getBuildingPlanTaskList,
  exPortBuildingPlanTaskList,
  getDevicePlanTaskList
} from "@/api/plan-produce/task";
import facDetail from "./fac-detail.vue";
import { tansParams, blobValidate } from "@/utils/ruoyi";
export default {
  components: { facDetail },
  data() {
    return {
      visible: false,
      facDetailVisible: false,
      loading: false,

      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      totalAll: [],
      // 显示搜索条件
      showSearch: true,
      // 非多个禁用
      multiple: true,
      ids1: [],
      floorList: [],
      dataForm: {},
      devicesVisible: false,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      idList: [],
      // 查询参数
      queryParams: {
        systemId: null,
        deviceId: null,
        pageNum: 1,
        pageSize: 10,
      },
      queryAll: {},
      activeName: "second",
      systemOptions: [],
      facOptions: [],
      tabList: [],
      tableList: [],
      total: 0,
      expandLoading: false
    };
  },
  computed: {},
  watch: {},
  created() { },
  mounted() { },
  methods: {
    init(list) {
      this.dataForm.id = list.id || 0;
      this.queryParams.systemId = null;
      this.queryParams.deviceId = null;
      this.visible = true;
      this.$nextTick(() => {
        this.tableList = []
        if (this.dataForm.id) {
          this.loading = true;
          getPlanTaskListQuery(list.id).then((res) => {
            this.systemOptions = res.data;
            this.loading = false;
          });
          // 查询楼栋
          getProjectPlanBuildingList(list.id).then((res) => {
            if (res.data.length) {
              this.activeName = res.data[0].id + "";
              this.tabList = res.data;
              getBuildingPlanTaskList({
                buildingId: res.data[0].id,
                subPlanId: list.id,
              }).then((list) => {
                // this.tableList = list.rows;
                for (let i = 0; i < list.rows.length; i++) {
                  this.tableList.push({
                    ...list.rows[i],
                    children: []
                  })
                }
                this.total = list.total;
              });
            }
          });
        }
      });
    },
    getList() {
      this.tableList = []
      getBuildingPlanTaskList({
        ...this.queryParams,
        buildingId: this.activeName,
        subPlanId: this.dataForm.id,
      }).then((list) => {
        for (let i = 0; i < list.rows.length; i++) {
          this.tableList.push({
            ...list.rows[i],
            children: []
          })
        }
        this.total = list.total;
      });
    },
    getTotal(row) {
      var Acc = 0
      for (let i = 0; i < this.totalAll.length; i++) {
        if (this.totalAll[i].id == row.floorId) {
          Acc = this.totalAll[i].total - 0
        }
      }
      return Acc
    },
    handlePagination(row, event) {
      // event 可能包含新的 pageNum 和 pageSize  
      // 你可以根据这些值来更新你的数据，比如重新请求对应行的子数据  
      // ... 更新数据的逻辑  
      this.queryAll[row.floorId] = event
      getDevicePlanTaskList({ ...row, ...event }).then(childrenData => {
        row.children = childrenData.rows; // 将获取到的数据设置到children属性中
        this.expandLoading = false; // 数据加载完成，停止加载状态  
      }).catch(error => {
        this.expandLoading = false; // 加载失败也停止加载状态  
      });
    },
    // 点击展开
    handleRowClick(row, expandedRows) {
      if (expandedRows.length && !row.children.length) { // 当行被展开且没有子数据时  
        this.expandLoading = true; // 开始加载数据
        // 初始化分页信息，如果还没有的话  
        if (!this.queryAll[row.floorId]) {
          this.queryAll[row.floorId] = { pageNum: 1, pageSize: 10 };
        }
        getDevicePlanTaskList({ ...row, ...this.queryAll[row.floorId] }).then(childrenData => {
          row.children = childrenData.rows; // 将获取到的数据设置到children属性中
          this.totalAll.push({
            total: childrenData.total,
            id: row.floorId
          })
          this.expandLoading = false; // 数据加载完成，停止加载状态  
        }).catch(error => {
          this.expandLoading = false; // 加载失败也停止加载状态  
        });
      } else {
        // 行被关闭，清除子数据（如果需要的话）  
        row.children = []; // 或者你可以设置一个标志来表示没有子数据，而不是清空数组  
        // 可能还需要更新分页信息或者其他相关状态  
      }

    },





    handleQuery() {
      this.getList();
    },
    resetQuery() {
      this.queryParams.systemId = null;
      this.queryParams.deviceId = null;
      this.getList();
    },
    bindDevice() {
      this.devicesVisible = true;
      this.idList = [...this.ids];
      this.$nextTick(() => {
        this.$refs.devices.init();
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      let data = {
        buildingId: this.activeName - 0,
        deviceId: this.queryParams.deviceId,
        subPlanId: this.dataForm.id,
        systemId: this.queryParams.systemId,
      };
      exPortBuildingPlanTaskList(data).then(async (res) => {
        const isBlob = blobValidate(res);
        const filename = ` 任务详情_${new Date().getTime()}.xlsx`;
        if (isBlob) {
          saveAs(res.data, filename);
        } else {
          const resText = await res.text();
          const rspObj = JSON.parse(resText);
          const errMsg =
            errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
          Message.error(errMsg);
        }
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 单独点击
    handleUpdate(id) {
      this.devicesVisible = true;
      this.idList = [id];
      this.$nextTick(() => {
        this.$refs.devices.init();
      });
    },
    // 刷新页面
    refreshDev(isrRefresh) {
      this.devicesVisible = false;
      if (isrRefresh) {
        this.loading = true;
        getBuildingFloorList(this.dataForm.id).then((res) => {
          this.floorList = res.data;
          this.loading = false;
        });
      }
    },
    //修改楼层别名
    updateFloorAlias(row) {
      let dataInfo = [
        {
          floor: row.floor,
          floorAlias: row.floorAlias,
          id: row.id,
        },
      ];
      updateBuildFloor(dataInfo).then((res) => {
        this.refreshDev(true);
      });
    },
    // 设备详情
    handleFacDetail(row) {
      this.facDetailVisible = true;
      this.$nextTick(() => {
        this.$refs.facDetail.init(row, this.queryParams);
      });
    },
    handleClick(tab, event) {
      this.activeName = tab.name;
      this.$nextTick(() => {
        this.getList();
      });
    },
    // 切换系统
    changeSystem() {
      this.queryParams.deviceId = "";
      for (let i = 0; i < this.systemOptions.length; i++) {
        if (this.systemOptions[i].id == this.queryParams.systemId) {
          this.facOptions = this.systemOptions[i].children;
          console.log(this.systemOptions[i], ">>>>>555");
        }
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.topSty {
  width: 98%;
  margin-bottom: 20px;
  display: flex;
  // justify-content: flex-end;
}
</style>
